package com.zs.grain.service


import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.core.content.ContextCompat.startActivity
import com.airbnb.lottie.parser.IntegerParser
import com.jeremyliao.liveeventbus.LiveEventBus
//import com.jeremyliao.liveeventbus.utils.AppUtils.getApplicationContext
import com.xnkj1688.semplibrary.entity.*
import com.xnkj1688.semplibrary.ulti.DateUtil
import com.zs.grain.tool.DataSync
import com.zslibrary.BusMaster.BusMaster
import java.text.SimpleDateFormat
import java.util.*

import javax.inject.Inject
import javax.inject.Singleton
import kotlin.collections.ArrayList

/**
 * Created by Wesley on 2017/7/15.
 */

@Singleton
class SignalRHub @Inject constructor(
    val mContext: Context,
    val mDataService: DataService
) {
    lateinit var mSignalRService: SignalRService

    fun onConnected() {
        mDataService.insertLog("State:网络连接成功")
        LiveEventBus.get("SignalR.Connected").post(true)
        var single = mSignalRService.sceneQr
        single.subscribe({
            LiveEventBus.get("SignalR.SceneQr").post(it)
        }, {
            it.printStackTrace()
            LiveEventBus.get("SignalR.SceneQr").post("")
        })
    }

    fun onDisconnected() {
        mDataService.insertLog("State:网络断开连接")
        LiveEventBus.get("SignalR.SceneQr").post("")
    }

    fun sendPayedNotify(orderId: Long?, payWay: Int?) {
        var payway = "支付宝"
        if(payWay==4) payway = "微信"
        mDataService.insertLog("Product:支付成功,收到服务端订单号:$orderId,支付方式:"+payway)//
        mSignalRService.reportResult("sendPayedNotify",true)
        //if (mDataService.currentOrder?.id!=orderId) return;
        if (orderId != mDataService.currentOrder?.id) {
            this.uploadOrder(orderId)
            mDataService.insertLog("Order:待支持订单与服务端接收到订单信息有差别")
            return
        }
        var bundle = Bundle()
        bundle.putLong("OrderId", orderId ?: 0)
        bundle.putInt("PayWay", payWay ?: 0)
        LiveEventBus.get("SignalR.Payed").post(bundle);
    }

    fun syncSettings(getType:String,mcb:Boolean,pcb:Boolean,scb:Boolean){

    }

    fun syncAdvs(getType:String){
        mSignalRService.settings
            .map {
                var server = mDataService.server;
//                mDataService.DaoSetting.deleteAll();
//                mDataService.DaoSetting.insertInTx(it.toList());
                if (server != mDataService.server)
                    mSignalRService.init("http://" + mDataService.server)
//                    this.terminalId.postValue(mDataService.terminalId.toString())
//                    this.verifyCode.postValue(mDataService.verifyCode)
//                    this.server.postValue(mDataService.server)

                //mDeviceService.init();
                it.size
            }
            .map {
                //uiNotify.postValue(super.getToastNotify("终端配置同步成功(${it}条)", Toast.LENGTH_SHORT))
                //mDataService.insertLog("$getType:终端配置同步成功(${it}条)")
            }
            .flatMap {
                mSignalRService.advertisements
            }.map {
                mDataService.DaoAdvertisement.deleteAll()
                mDataService.DaoAdvertisement.insertInTx(it.toList())
                it.size
            }.map {
                //uiNotify.postValue(super.getToastNotify("广告数据同步成功(${it}条)", Toast.LENGTH_SHORT))
                mDataService.insertLog("$getType:广告数据同步成功(${it}条)")
            }.subscribe({
                //uiNotify.postValue(super.getToastNotify("系统数据同步成功", Toast.LENGTH_SHORT))
                //mDataService.insertLog("$getType:系统数据同步成功")
                //LiveEventBus.get().with("RemotePush.pushFinish").post(true)
                var bundle = Bundle()
                bundle.putString("UI", "Menus")
                LiveEventBus.get("SwitchUI").post(bundle)
            }, {
                //uiNotify.postValue(super.getToastNotify("系统数据同步失败",Toast.LENGTH_SHORT))
                mDataService.insertLog("$getType:广告数据同步失败")
            })
        LiveEventBus.get("RemotePush.refreshPlayer").post(true)
    }

    fun updateSettings() {
        mDataService.insertLog("RemotePush:更新设置")
        LiveEventBus.get("RemotePush.updateSettings").post(true)
        mSignalRService.reportResult("updateSetting",true).subscribe()
    }

    fun updateScene() {
        mDataService.insertLog("RemotePush:更新菜单配方")
        LiveEventBus.get("RemotePush.updateScene").post(true)
        mSignalRService.reportResult("updateScene",true).subscribe()
    }

    fun updateAdvertisements() {
        mDataService.insertLog("RemotePush:更新广告")
        LiveEventBus.get("RemotePush.updateAdvertisements").post(true)
        //syncAdvs("RemotePush")
    }

    fun maintanence(privilege: Int) {
        mDataService.insertLog("RemotePush:start maintanence:$privilege")
    }

    @SuppressLint("WrongConstant")
    fun takeProduct(){
        mDataService.insertLog("RemotePush:取饮料")
        BusMaster.getInstance(mContext).componentTest(5801,4)   //TODO:异步
    }

    @SuppressLint("WrongConstant")
    fun openBigDoor(){
        mDataService.insertLog("RemotePush:开大门")
        BusMaster.getInstance(mContext).componentTest(2001,0)   //TODO:异步
        mSignalRService.reportResult("openBigDoor",true)
    }

    fun reboot() {
        mDataService.insertLog("RemotePush:远程重启")
        mSignalRService.reportResult("openBigDoor",true)
        BusMaster.getInstance(mContext).resetBoard()
        val componetName =  ComponentName("com.example.reboottest","com.example.reboottest.MainActivity");
        val intent =  Intent();
        intent.setComponent(componetName);
        mContext.startActivity(intent)
    }

    //tinn 2020_07_17 ADD:
    fun fillIngredient(id:Integer,dose:Integer){
        var component=mDataService.getComponentsIngredient(id.toInt())
        component.count+=dose.toInt()
        component.fillingTime= Date()
        mDataService.update(component)
        var components=ArrayList<Component>()
        components.add(component)
        mSignalRService.uploadComponents(components)
    }

    fun clean() {
        mDataService.insertLog("RemotePush:start clean")
    }

    fun uploadOrder(orderId: Long?) {
        LiveEventBus.get("RemotePush:start SyncService.UploadOrder").post(orderId)
    }

    fun notifyUpdateTrack(counterNo: Int?, no: Int?) {
        val intent = Intent(SignalRHub.MESSAGE_UPDATE_TRACK_ACTION)
        intent.putExtra("CounterNo", counterNo)
        intent.putExtra("No", no)
        mContext.sendBroadcast(intent)
    }

    fun notifyUpdateTracks() {
        val intent = Intent(SignalRHub.MESSAGE_UPDATE_TRACKS_ACTION)
        mContext.sendBroadcast(intent)
    }

    fun notifyUpdateSettings() {
        val intent = Intent(SignalRHub.MESSAGE_UPDATE_SETTINGS_ACTION)
        mContext.sendBroadcast(intent)
    }

    fun notifyUploadData() {
        val intent = Intent(SignalRHub.MESSAGE_UPLOAD_DATA_ACTION)
        mContext.sendBroadcast(intent)
    }

    fun notifyTestTrack(counterNo: Int?, no: Int?) {
        val intent = Intent(SignalRHub.MESSAGE_TEST_TRACK_ACTION)
        intent.putExtra("CounterNo", counterNo)
        intent.putExtra("No", no)
        mContext.sendBroadcast(intent)
    }

    fun notifyTestTracks() {
        val intent = Intent(SignalRHub.MESSAGE_TEST_TRACKS_ACTION)
        mContext.sendBroadcast(intent)
    }

    companion object {
        val MESSAGE_PAYED_ACTION = "com.zs.grain.MESSAGE_PAYED_ACTION"
        val MESSAGE_UPDATE_TRACK_ACTION = "com.zs.grain.MESSAGE_UPDATE_TRACK_ACTION"
        val MESSAGE_UPDATE_TRACKS_ACTION = "com.zs.grain.MESSAGE_UPDATE_TRACKS_ACTION"
        val MESSAGE_UPDATE_SETTINGS_ACTION = "com.zs.grain.MESSAGE_UPDATE_SETTINGS_ACTION"
        val MESSAGE_TEST_TRACK_ACTION = "com.zs.grain.MESSAGE_TEST_TRACK_ACTION"
        val MESSAGE_TEST_TRACKS_ACTION = "com.zs.grain.MESSAGE_TEST_TRACKS_ACTION"
        val MESSAGE_UPLOAD_DATA_ACTION = "com.zs.grain.MESSAGE_UPLOAD_DATA_ACTION"
        val MESSAGE_MAKE_REQUEST_ACTION = "com.zs.grain.MESSAGE_MAKE_REQUEST_ACTION"
        val MESSAGE_HUB_ACTION = "com.zs.grain.MESSAGE_HUB_ACTION"
    }
}
